//
//  XHRSubTagViewController.m
//  BuDeJie
//
//  Created by haoran on 16/4/5.
//  Copyright © 2016年 xuhaoran. All rights reserved.
//

#import "XHRSubTagViewController.h"
#import <AFNetworking/AFNetworking.h>
#import "XHRSubTagCell.h"
#import "XHRSubTagItem.h"
#import <MJExtension/MJExtension.h>
#import <SVProgressHUD/SVProgressHUD.h>

@interface XHRSubTagViewController ()

/** 模型数组 **/
@property (nonatomic, strong) NSArray *itemArray;
/** 网络请求任务 **/
@property (nonatomic, weak) NSURLSessionDataTask *task;
@end

@implementation XHRSubTagViewController

static NSString * const ID = @"cell";
// 让分割线全屏 -> 1.自定义分割线 2.利用系统属性(iOS6->iOS7 , iOS7 -> iOS8)不能支持iOS8 3.重写cell的setFrame1.取消系统的分割线 2.设置tableView背景色为分割线颜色
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //设置标题
    self.title = @"推荐标签";
    
    //加载数据
    [self loadData];
    
    // 注册cell
    [self.tableView registerNib:[UINib nibWithNibName:@"XHRSubTagCell" bundle:nil] forCellReuseIdentifier:ID];
    
    //取消系统的分割线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //设置tableview背景色
    self.tableView.backgroundColor = XHRColor(215, 215, 215);
}

-(void)viewWillDisappear:(BOOL)animated{
    
    
    [super viewWillDisappear:animated];
    
    //关闭指示器
    [SVProgressHUD dismiss];
    // 取消请求 不然还在发送网络请求
    [self.task cancel];
}

#pragma mark ---- 加载数据
-(void)loadData{
    // 查看接口文档 -> 发送请求 -> 解析数据
    //1.创建请求会话管理者
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    
    //2.创建请求参数
    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    dict[@"a"] = @"tag_recommend";
    dict[@"c"] = @"topic";
    dict[@"action"] = @"sub";

    //提示用户
    [SVProgressHUD showWithStatus:@"正在加载..."];
    
 
    //3.发送请求
    self.task = [manager GET: @"http://api.budejie.com/api/api_open.php" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSMutableArray * responseObject) {
        //成功回调
        //字典数组转模型
        self.itemArray =  [XHRSubTagItem mj_objectArrayWithKeyValuesArray:responseObject];
        
        //移除指示器
        [SVProgressHUD dismiss];
        //刷新表格
        [self.tableView reloadData];
     
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //失败回调
        NSLog(@"%@",error);
    }];

}





#pragma mark - Table view data source



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //返回模型数组数量
    return self.itemArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XHRSubTagCell *cell = [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];
    
    //设置为0
//    cell.layoutMargins = UIEdgeInsetsZero;
    
    cell.item = self.itemArray[indexPath.row];
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 60;
}

@end
